/*
 * @Author: rogi
 * @Date: 2022-07-18 15:42:48
 * @LastEditTime: 2022-12-07 17:06:03
 * @LastEditors: rogi
 * @Description: 描述
 */
import { ElNotification } from 'element-plus';
import Cookie from 'js-cookie';
import { useRouter } from 'vue-router';
const router = useRouter();
import store from '../store/index.js';
import { write,read} from "@/utils/storage";
import { host } from '@/utils/config.js'
import sdk from '@/sdk/index'

export default (url, option = {}) => {
  url = host.requestHost + url
  return new Promise((resolve, rejects) => {
    const {
      method = 'get', // 请求方式, 默认get
      body = JSON.stringify({}), // post传递参数
      params = JSON.stringify({}), // get传递的参数
      showToast = true
    } = option;
    if ((method === 'get' || method === 'delete') && params !== "{}") {
      Object.keys(params).forEach(el => {
        if(url.indexOf('?') === -1) {
          url += `?${el}=${params[el]}`
        } else {
          url += `&${el}=${params[el]}`
        }
      })
      delete option.body
    } else if (method === 'post' || method === 'put') {
      option.body = JSON.stringify(body)
      delete option.params
    };
    fetch(url, {
      ...option,
      headers: {
        'Content-Type': 'application/json',
        'X-Access-Token': read('X-Access-Token') || '',
        "Authorization": sessionStorage.getItem('access_token') || "",
        "enterprise_id": sessionStorage.getItem('enterprise_id') || "",
        "expires_in": sessionStorage.getItem('expires_in') || "",
        "user_id": sessionStorage.getItem('user_id') || "",
        "user_type": sessionStorage.getItem('user_type') || "",
        "merchant_id": sessionStorage.getItem('merchant_id') || "",
      },
    }).then(res => {
      if (res.status === 401) {
        store.commit('common/USER_LOGIN_OUT')
        rejects()
      }
      return res.text()
    }).then(async (data) => {
      const resData = JSON.parse(data);
      if (resData.code === 406) {
        const res = await sdk.getUserInfo()
        sessionStorage.setItem('access_token', res.data.access_token)
        sessionStorage.setItem('enterprise_id', res.data.enterprise_id)
        sessionStorage.setItem('expires_in', res.data.expires_in)
        sessionStorage.setItem('user_id', res.data.user_id)
        sessionStorage.setItem('user_type', res.data.user_type)
        window.location.href = '/'
        return false
      } else if (resData.code === 500) {
        ElNotification({
          title: `系统异常，请联系管理人员`,
          type: 'error',
        })
        return false
      }
      if (resData.code !== 0 && resData.code !== 200 && resData.status !== 0) {
        rejects(resData)
        ElNotification({
          title: resData.msg,
          type: 'error',
        })
        return false
      }
      if (method !== 'get' && showToast) {
        ElNotification({
          title: resData.msg,
          type: 'success',
        })
      }
      resolve(resData)
    }).catch(err => {
      rejects(err)
    })
  })
}
